<template>
  <div>
    <!-- <TableSearch :query="query" :options="searchOpt" :search="handleSearch" /> -->
    <div class="container">
      <TableCustom
        :columns="columns"
        :tableData="tableData"
        :total="page.total"
        :currentPage="page.currPage"
        :viewFunc="handleView"
        :delFunc="handleDelete"
        :change-page="changePage"
        :editFunc="handleEdit"
        :yichRecommendedFunc="handleYichRecommended"
      >
        <template #toolbarBtn>
          <el-button type="warning" :icon="CirclePlusFilled" @click="handleAdd"
            >添加</el-button
          >
        </template>
        <!-- 歌曲/专辑封面 -->
        <template #coverUrl="{ rows }">
          <el-image
            :src="rows.coverUrl.indexOf('http') === -1 ? '' : 'rows.coverUrl'"
            fit="cover"
            class="avatar"
          ></el-image>
        </template>
        <!-- 歌词类型：0-无 1-静态，2-LRC，3-KRC -->
        <template #lyricType="{ rows }">
          <el-popover
            effect="light"
            trigger="hover"
            placement="top"
            width="auto"
          >
            <template #default>
              <div>下载歌词</div>
            </template>
            <template #reference>
              {{
                rows.lyricType === 1
                  ? "静态"
                  : rows.lyricType === 2
                  ? "LRC"
                  : rows.lyricType === 3
                  ? "KRC"
                  : "无"
              }}
            </template>
          </el-popover>
        </template>
        <!-- 时长 -->
        <template #duration="{ rows }">
          <div>{{ secondsToHms(rows.duration) }}</div>
        </template>
      </TableCustom>
    </div>
    <el-dialog
      :title="isEdit ? '编辑' : '新增'"
      v-model="visible"
      width="700px"
      destroy-on-close
      :close-on-click-modal="closeDialog"
      @close="closeDialog"
    >
      <TableEdit
        :form-data="rowData"
        :options="options"
        :edit="isEdit"
        :update="updateData"
        @closeDialogP="closeDialog"
      />
    </el-dialog>
    <el-dialog title="详情" v-model="visible1" width="700px" destroy-on-close>
      <TableDetail
        :data="viewData"
        @closeDialogP="visible1 = false"
      ></TableDetail>
    </el-dialog>

    <!-- 上新歌曲---歌曲列表弹框--选择歌曲并且设为推荐 -->
    <el-drawer
      v-model="drawer2"
      direction="rtl"
      title="歌曲列表"
      :before-close="handleClose"
      append-to-body
      size="60%"
    >
      <MusicLibraryList
        ref="childRef2"
        :isDrawer="drawer2"
        @parentMethodTriggered="getData"
      ></MusicLibraryList>
    </el-drawer>
  </div>
</template>

<script setup lang="ts" name="system-user">
import { ref, reactive } from "vue";
import { ElMessage } from "element-plus";
import { CirclePlusFilled } from "@element-plus/icons-vue";
import { User } from "@/types/user";
import { fetchDeleteCategor } from "@/api/configuration";
import { fetchAdvertisementCreate } from "@/api/advertisementManage";
import { fetchRecommendedList } from "@/api/configuration";
import { fetchDeleteRecommended } from "@/api/musicLibrary";
import TableCustom from "@/components/table-custom.vue";
import TableDetail from "@/components/table-detail.vue";
import TableSearch from "@/components/table-search.vue";
import { FormOption, FormOptionList } from "@/types/form-option";
import MusicLibraryList from "@/views/configuration/musicLibraryList.vue";

// 时长换算
const secondsToHms = (seconds) => {
  const hours = Math.floor(seconds / 3600);
  const minutes = Math.floor((seconds % 3600) / 60);
  const secs = seconds % 60;
  return `${minutes.toString().padStart(2, "0")}:${secs
    .toString()
    .padStart(2, "0")}`;
};

// 查询相关
const query = reactive({
  keyword: "",
});
const searchOpt = ref<FormOptionList[]>([
  { type: "input", label: "标签名称：", prop: "keyword" },
]);
const handleSearch = () => {
  changePage(1);
};

// 表格相关
let columns = ref([
  { type: "index", label: "序号", width: 80, align: "center" },
  // { prop: "songId", label: "歌曲ID", width: 150 },
  // { prop: "coverUrl", label: "歌曲/专辑封面", width: 150 },
  { prop: "songName", label: "歌曲名称" },
  // { prop: "tagNameList", label: "歌曲标签", width: 150 },
  // { prop: "songDesc", label: "歌曲描述" },
  // { prop: "songVersion", label: "歌曲版本", width: 150 },
  // { prop: "performer", label: "表演者", width: 150 },
  // { prop: "lyricist", label: "词作者", width: 150 },
  // { prop: "composer", label: "曲作者", width: 150 },
  // { prop: "lyricType", label: "歌词类型", width: 150 }, //歌词类型：0-无 1-静态，2-LRC，3-KRC
  { prop: "copyrightOwner", label: "版权方" },
  // { prop: "manufacturer", label: "厂商", width: 150 },
  // { prop: "recordLabel", label: "厂牌", width: 150 },
  { prop: "albumName", label: "专辑名" },
  // { prop: "bpm", label: "BPM", width: 150 },
  { prop: "duration", label: "时长" },
  { prop: "createTime", label: "创建时间" },
  { prop: "operator3", label: "操作", width: 200, fixed: "right" },
]);
const page = reactive({
  currPage: 1,
  size: 10,
  total: 0,
});
const tableData = ref([]);
const getData = async () => {
  console.log("有没有触发父组件的方法呢？");
  const res = await fetchRecommendedList({});
  console.log("获取歌曲上新推荐列表");
  let list = res.data.data;
  if (list.length > 0) {
    list.forEach((item) => {
      if (Array.isArray(item.categoryNameList)) {
        item.categoryNameList = item.categoryNameList.join(",");
      }
      if (Array.isArray(item.tagNameList)) {
        item.tagNameList = item.tagNameList.join(",");
      }
      item.pageName = "songRecommendList";
    });
  }
  tableData.value = list;
  console.log(tableData.value);
  page.total = tableData.value.length;
  console.log(page.total);
};
getData();

// 分页
const changePage = (val: number) => {
  console.log("点击分页---歌单分类管理");

  page.currPage = val;
  console.log(page.currPage);
  getData();
};

// 新增/编辑弹窗相关
let options = ref<FormOption>({
  labelWidth: "100px",
  span: 24,
  list: [],
});
const visible = ref(false);
const isEdit = ref(false);
const rowData = ref({});

// 上新歌曲--抽屉
const drawer2 = ref(false);
const handleClose = (done: () => void) => {
  done();
};

const childRef2 = ref(null);
// 新增
const handleAdd = (row) => {
  console.log("新增");
  console.log(row);
  drawer2.value = true;
  setTimeout(() => {
    if (childRef2.value) {
      childRef2.value.getData();
    }
  }, 100);
};

// 编辑
const handleEdit = (row) => {
  console.log("编辑");
  rowData.value = { ...row };
  isEdit.value = true;
  visible.value = true;
};
const updateData = async (data) => {
  data.imgUrl = data.coverUrl;
  let datas = {};
  let obj = { advertisementId: data.advertisementId };
  if (isEdit.value) {
    datas = { ...obj, ...data };
  } else {
    datas = { ...data };
  }
  console.log("最终编辑或者新增的数据---是");
  console.log(datas);
  const res = await fetchAdvertisementCreate(datas);
  console.log("创建广告");
  console.log(res.data);
  closeDialog();
  getData();
};

const closeDialog = () => {
  visible.value = false;
  isEdit.value = false;
};

// 详情弹窗相关
const visible1 = ref(false);
const viewData = ref({
  row: {},
  list: [],
});
const handleView = (row) => {
  viewData.value.row = { ...row };
  viewData.value.list = [
    {
      prop: "playlistCategoryId",
      label: "分类ID",
    },
    {
      prop: "categoryName",
      label: "分类名称",
    },
    {
      prop: "categoryDesc",
      label: "分类描述",
    },
    {
      prop: "playlistCount",
      label: "歌单数量",
    },
    {
      prop: "createTime",
      label: "创建时间",
    },
    {
      prop: "canModified",
      label: "能否编辑",
    },
  ];
  visible1.value = true;
};

// 删除相关
const handleDelete = async (row) => {
  console.log("删除");
  console.log(row);
  let datas = {
    id: row.playlistCategoryId,
  };
  const res = await fetchDeleteCategor(datas);
  if (res.data.code == 0) {
    ElMessage.success("删除成功");
    getData();
  }
};

// 上新推荐列表--移
// 移除上新推荐
const handleYichRecommended = async (row) => {
  console.log("歌曲-移除上新推荐");
  let params = {
    songId: row.songId,
  };
  const res = await fetchDeleteRecommended(params);
  if (res.data.code === 0) {
    ElMessage.success("移除成功");
    getData();
  } else {
    ElMessage.error(res.data.msg);
  }
};
</script>

<style scoped>
.avatar {
  width: 100px;
  height: 100px;
  margin: 0 auto;
  background-size: contain;
  background-repeat: no-repeat;
  background-position: center center;
}
</style>
